import 'package:flutter/material.dart';
import 'package:im_flutter_sdk_example/jsonserialize/comment/data.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';

class CommentModelProvider with ChangeNotifier {
  List<CommentData> _currentComments = new List<CommentData>();

  List<CommentData> get list => _currentComments;

  String commentPlaceHolderText = '发表您的评论吧';
  bool isReplay = false; //是否是回复
  String currentCommentId = ''; //当前评论id
  String newsId = '';
  int newsType = 0;

  //提交评论
  void postComment(
      String content, int type, String commentId, Function cb) async {
    var result = await G.req.comment
        .addComment(content: content, commentType: type, objId: commentId);
    if (result.data['status'] == 1) {
      G.toast(result.data['message']);
      loadUserComments(commentId, type);
      cb();
    }
  }

  //回复评论
  void replayComment(
      String content, int type, String newsId, Function cb) async {
    var result = await G.req.comment.replayComment(
        content: content,
        commentType: type,
        commentId: currentCommentId,
        objId: newsId);
    if (result.data['status'] == 1) {
      G.toast(result.data['message']);
      loadUserComments(newsId, type);
      cb();
    }
  }

  //加载评论
  void loadUserComments(String objId, int type) async {
    _currentComments.clear();
    newsId = objId;
    newsType = type;
    var result =
        await G.req.comment.commentList(commentId: objId, commentType: type);
    if (result.data['status'] == 1) {
      result.data['data'].forEach((item) {
        CommentData comment = CommentData.fromJson(item);
        _currentComments.add(comment);
      });
      notifyListeners();
    }
  }

  ///修改占位符内容
  modifyPlaceHolder(String name) {
    commentPlaceHolderText = '回复@$name:';
    isReplay = true;
    notifyListeners();
  }

  //重置占位符内容 +  清空当前评论id
  resetPlaceHolder() {
    commentPlaceHolderText = '发表您的评论吧';
    isReplay = false;
    currentCommentId = '';
    notifyListeners();
  }

  //设置当前回复id+
  setCurrentId(String commentId) {
    currentCommentId = commentId;
  }

  //点赞
  thumbsUp(String commentId) async {
    var result = await G.req.comment.givelike(commentId: commentId);
    if (result.data['status'] == 1) {
      loadUserComments(newsId, newsType);
    }
  }

  //取消点赞
  thumbsDown(String commentId) async {
    var result = await G.req.comment.downlike(commentId: commentId);
    if (result.data['status'] == 1) {
      loadUserComments(newsId, newsType);
    }
  }
}
